<?php

namespace app\api\controller;
/**
 * ============================================================================
 * DSKMS多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 用户账号控制器
 */
class  Memberaccount extends MobileMember
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * @api {POST} api/Memberaccount/bind_mobile_step1 绑定手机第一步
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} mobile 手机号
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.sms_time 倒计时时间（秒）
     */
    public function bind_mobile_step1()
    {
        if (!input('post.mobile') || !preg_match('/^\d{11}$/', input('post.mobile'))) {
            ds_json_encode(10001, '请正确输入手机号', ['code' => '']);
        }


        $member_model = model('member');
        $check_mobile = $member_model->getMemberInfo(array(
            'member_mobile' => trim(input('post.mobile')),
            'member_mobilebind' => 1
        ));
        if (is_array($check_mobile) and count($check_mobile) > 0) {
            ds_json_encode(10001, '手机号码已经被绑定过', ['code' => '']);
        }
        //验证发送频率
        $verify_code_model = model('verify_code');
        $result = $verify_code_model->isVerifyCodeFrequant(4, 1);
        if (!$result['code']) {
            ds_json_encode(10001, $result['msg'], ['code' => '']);

        }

        $verify_code = $verify_code_model->genVerifyCode(4, 1);
        if (!$verify_code) {
            ds_json_encode(10001, '系统发生错误', ['code' => '']);

        }

        try {

            $mailtemplates_model = model('mailtemplates');
            $tpl_info = $mailtemplates_model->getTplInfo(array('mailmt_code' => 'modify_mobile'));
            $param = array();
            $param['code'] = $verify_code;
            $ten_param=array($param['code']);
            $message = ds_replace_text($tpl_info['mailmt_content'], $param);
            $smslog_param=array(
                    'ali_template_code'=>$tpl_info['ali_template_code'],
                    'ali_template_param'=>$param,
                    'ten_template_code'=>$tpl_info['ten_template_code'],
                    'ten_template_param'=>$ten_param,
                    'message'=>$message,
                );
            //发送短信
            $result = model('smslog')->sendSms(input('post.mobile'), $smslog_param,4,$verify_code);

            if ($result['state']) {
                $ip = request()->ip();
                $flag = $verify_code_model->addVerifyCode(array(
                    'verify_code_type' => 4,
                    'verify_code' => $verify_code,
                    'verify_code_user_type' => 1,
                    'verify_code_user_id' => $this->member_info['member_id'],
                    'verify_code_user_name' => $this->member_info['member_name'],
                    'verify_code_add_time' => TIMESTAMP,
                    'verify_code_ip' => $ip,
                ));
                if (!$flag) {
                    ds_json_encode(10001, '系统发生错误');

                }
                $updates = array();
                $updates['member_mobilebind'] = 0;
                $updates['member_mobile'] = input('post.mobile');
                $member_model->editMember(array('member_id' => $this->member_info['member_id']), $updates,$this->member_info['member_id']);
                ds_json_encode(10000, '发送成功', array('sms_time' => DEFAULT_CONNECT_SMS_TIME));
            } else {
                ds_json_encode(10001, $result['message']);
            }
        } catch (\Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
    }

    /**
     * @api {POST} api/Memberaccount/bind_mobile_step2 绑定手机第二步 - 验证短信码
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} auth_code 验证码
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function bind_mobile_step2()
    {
        if (!input('post.auth_code') || !preg_match('/^\d{6}$/', input('post.auth_code'))) {
            ds_json_encode(10001, '请正确输入短信验证码', ['code' => '-1']);
        }
        $member_model = model('member');

        $verify_code = input('post.auth_code');
        $validate_data = array(
            'verify_code' => $verify_code,

        );
        $verify_code_validate = ds_validate('verify_code');
        if (!$verify_code_validate->scene('verify_code_search')->check($validate_data)) {

            ds_json_encode(10001, $verify_code_validate->getError(), ['code' => '-1']);
        }
        $verify_code_model = model('verify_code');
        if (!$verify_code_model->getVerifyCodeInfo(array(array('verify_code_type' ,'=', 4), array('verify_code_user_type' ,'=', 1), array('verify_code_user_id' ,'=', $this->member_info['member_id']), array('verify_code' ,'=', $verify_code),  array('verify_code_add_time','>', TIMESTAMP - VERIFY_CODE_INVALIDE_MINUTE * 60)))) {

            ds_json_encode(10001, '验证失败', ['code' => '-1']);
        }


        $updates = array();
        $updates['member_mobilebind'] = 1;
        $update = $member_model->editMember(array('member_id' => $this->member_info['member_id']), $updates,$this->member_info['member_id']);
        if (!$update) {
            ds_json_encode(10001, '系统发生错误');
        }
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }

    /**
     * @api {POST} api/Memberaccount/bind_email_step1 绑定邮箱第一步
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} email 邮箱
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.sms_time 倒计时时间（秒）
     */
    public function bind_email_step1()
    {
        if (!input('post.email') || !preg_match('/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/', input('post.email'))) {
            ds_json_encode(10001, '请正确输入邮箱号', ['code' => '']);
        }


        $member_model = model('member');
        $check_email = $member_model->getMemberInfo(array(
            'member_email' => trim(input('post.email')),
            'member_emailbind' => 1
        ));
        if (is_array($check_email) and count($check_email) > 0) {
            ds_json_encode(10001, '邮箱号码已经被绑定过', ['code' => '']);
        }
        //验证发送频率
        $verify_code_model = model('verify_code');
        $result = $verify_code_model->isVerifyCodeFrequant(4, 1);
        if (!$result['code']) {
            ds_json_encode(10001, $result['msg'], ['code' => '']);

        }

        $verify_code = $verify_code_model->genVerifyCode(4, 1);
        if (!$verify_code) {
            ds_json_encode(10001, '系统发生错误', ['code' => '']);

        }

        try {

            $uid = base64_encode(ds_encrypt($this->member_info['member_id'] . ' ' . input('post.email')));
            $verify_url = HOME_SITE_URL . '/Login/bind_email.html?uid=' . $uid . '&hash=' . md5($verify_code);

            $mailtemplates_model = model('mailtemplates');
            $tpl_info = $mailtemplates_model->getTplInfo(array('mailmt_code' => 'bind_email'));
            $param = array();
            $param['site_name'] = config('ds_config.site_name');
            $param['user_name'] = $this->member_info['member_name'];
            $param['verify_url'] = $verify_url;
            $subject = ds_replace_text($tpl_info['mailmt_title'], $param);
            $message = ds_replace_text($tpl_info['mailmt_content'], $param);

            //发送短信
            $email = new \sendmsg\Email();
            $result['state'] = $email->send_sys_email(input('post.email'), $subject, $message);

            if ($result['state']) {
                $ip = request()->ip();
                $flag = $verify_code_model->addVerifyCode(array(
                    'verify_code_type' => 5,
                    'verify_code' => $verify_code,
                    'verify_code_user_type' => 1,
                    'verify_code_user_id' => $this->member_info['member_id'],
                    'verify_code_user_name' => $this->member_info['member_name'],
                    'verify_code_add_time' => TIMESTAMP,
                    'verify_code_ip' => $ip,
                ));
                if (!$flag) {
                    ds_json_encode(10001, '系统发生错误');

                }
                $updates = array();
                $updates['member_emailbind'] = 0;
                $updates['member_email'] = input('post.email');
                $member_model->editMember(array('member_id' => $this->member_info['member_id']), $updates,$this->member_info['member_id']);
                ds_json_encode(10000, '发送成功', array('sms_time' => DEFAULT_CONNECT_SMS_TIME));
            } else {
                ds_json_encode(10001, '邮箱发送失败');
            }
        } catch (\Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
    }


    /**
     * 检测会员手机是否绑定
     * 更改绑定手机 第一步 - 得到已经绑定的手机号
     * 修改密码 第一步 - 得到已经绑定的手机号
     * 修改支付密码 第一步 - 得到已经绑定的手机号
     */
    public function get_mobile_info()
    {
        $data = array();
        $data['state'] = $this->member_info['member_mobilebind'] ? true : false;
        $data['mobile'] = $data['state'] ? encrypt_show($this->member_info['member_mobile'], 4, 4) : $this->member_info['member_mobile'];
        ds_json_encode(10000, '', $data);
    }

    /**
     * 检测是否设置了支付密码
     */
    public function get_paypwd_info()
    {
        $data = array();
        $data['state'] = $this->member_info['member_paypwd'] ? true : false;
        ds_json_encode(10000, '', $data);
    }

    /**
     * @api {POST} api/Memberaccount/send_auth_code 统一发送身份验证码
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} type 类型
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.sms_time 倒计时时间（秒）
     */
    public function send_auth_code()
    {
        $type = input('post.type');
        if (!in_array($type, array('email', 'mobile'))) {
            ds_json_encode(10001, lang('param_error'));
        }

        if ($type == 'mobile' && (!$this->member_info['member_mobilebind'] || !$this->member_info['member_mobile'])) {
            ds_json_encode(10001, '您还未绑定手机号码');
        }
        if ($type == 'email' && (!$this->member_info['member_emailbind'] || !$this->member_info['member_email'])) {
            ds_json_encode(10001, '您还未绑定邮箱号');
        }

        $member_model = model('member');
        //验证发送频率
        $verify_code_model = model('verify_code');
        $result = $verify_code_model->isVerifyCodeFrequant(6, 1);
        if (!$result['code']) {
            ds_json_encode(10001, $result['msg']);

        }

        $verify_code = $verify_code_model->genVerifyCode(6, 1);
        if (!$verify_code) {
            ds_json_encode(10001, '系统发生错误');

        }

        try {

            $tpl_info = model('mailtemplates')->getTplInfo(array('mailmt_code' => 'authenticate'));
            $param = array();
            $ali_template_param=array();
            $param['code'] = $verify_code;
            $ali_template_param=$param;
            $param['site_name'] = config('ds_config.site_name');
            $ten_template_param=array($param['code']);
            $subject = ds_replace_text($tpl_info['mailmt_title'], $param);
            $message = ds_replace_text($tpl_info['mailmt_content'], $param);

            if ($type == 'email') {
                $email = new \sendmsg\Email();
                $result['state'] = $email->send_sys_email($this->member_info["member_email"], $subject, $message);
            } elseif ($type == 'mobile') {
                $smslog_param=array(
                    'ali_template_code'=>$tpl_info['ali_template_code'],
                    'ali_template_param'=>$ali_template_param,
                    'ten_template_code'=>$tpl_info['ten_template_code'],
                    'ten_template_param'=>$ten_template_param,
                    'message'=>$message,
                );
                $result = model('smslog')->sendSms($this->member_info['member_mobile'], $smslog_param,5,$verify_code);
            }


            if ($result['state']) {
                $ip = request()->ip();
                $flag = $verify_code_model->addVerifyCode(array(
                    'verify_code_type' => 6,
                    'verify_code' => $verify_code,
                    'verify_code_user_type' => 1,
                    'verify_code_user_id' => $this->member_info['member_id'],
                    'verify_code_user_name' => $this->member_info['member_name'],
                    'verify_code_add_time' => TIMESTAMP,
                    'verify_code_ip' => $ip,
                ));
                if (!$flag) {
                    ds_json_encode(10001, '系统发生错误');

                }
                ds_json_encode(10000, '发送成功', array('sms_time' => DEFAULT_CONNECT_SMS_TIME, 'state' => '1'));
            } else {
                ds_json_encode(10001, $result['message'], ['code' => '']);
            }
        } catch (\Exception $e) {
            ds_json_encode(10001, $e->getMessage(), ['code' => '']);
        }
    }

    /**
     * @api {POST} api/Memberaccount/check_auth_code 统一验证身份验证码
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} auth_code 验证码
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function check_auth_code()
    {
        $verify_code = input('post.auth_code');
        $validate_data = array(
            'verify_code' => $verify_code,

        );
        $verify_code_validate = ds_validate('verify_code');
        if (!$verify_code_validate->scene('verify_code_search')->check($validate_data)) {

            ds_json_encode(10001, $verify_code_validate->getError());
        }
        $verify_code_model = model('verify_code');
        if (!$verify_code_model->getVerifyCodeInfo(array(array('verify_code_type' ,'=', 6), array('verify_code_user_type' ,'=', 1), array('verify_code_user_id' ,'=', $this->member_info['member_id']), array('verify_code' ,'=', $verify_code), array('verify_code_add_time','>', TIMESTAMP - VERIFY_CODE_INVALIDE_MINUTE * 60)))) {

            ds_json_encode(10001, '验证失败');
        }
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }

    private function _modify_pwd_limit_check()
    {
        //身份验证后，需要在30分钟内完成修改密码操作

        $verify_code_model = model('verify_code');
        if (!$verify_code_model->getVerifyCodeInfo(array(array('verify_code_type' ,'=', 6), array('verify_code_user_type' ,'=', 1), array('verify_code_add_time','>', TIMESTAMP - 30 * 60)))) {

            ds_json_encode(10001, '验证失败', ['code' => '']);
        }
    }

    /**
     * @api {POST} api/Memberaccount/modify_password 更改密码 - 保存新密码到数据库
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} password 原密码
     * @apiParam {String} password1 新密码
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function modify_password()
    {
        if (!input('post.password') || !input('post.password1') || input('post.password') != input('post.password1')) {
            ds_json_encode(10001, '提交数据错误', ['code' => '']);
        }

        //身份验证后，需要在30分钟内完成修改密码操作
        $this->_modify_pwd_limit_check();

        $member_model = model('member');

        $update = $member_model->editMember(array('member_id' => $this->member_info['member_id']), array('member_password' => md5(input('post.password'))),$this->member_info['member_id']);
        if (!$update) {
            ds_json_encode(10001, '密码修改失败', ['code' => '']);
        }


        ds_json_encode(10000, lang('ds_common_op_succ'));
    }


     /**
     * @api {POST} api/Memberaccount/modify_password 更改支付密码 - 保存新密码到数据库
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} password 原密码
     * @apiParam {String} password1 新密码
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function modify_paypwd()
    {

        if (!input('post.password') || !input('post.password1') || input('post.password') != input('post.password1')) {
            ds_json_encode(10001, '提交数据错误', ['code' => '']);
        }

        //身份验证后，需要在30分钟内完成修改密码操作
        $this->_modify_pwd_limit_check();

        $member_model = model('member');
        $update = $member_model->editMember(array('member_id' => $this->member_info['member_id']), array('member_paypwd' => md5(input('post.password'))),$this->member_info['member_id']);
        if (!$update) {
            ds_json_encode(10001, '密码修改失败', ['code' => '']);
        }

        ds_json_encode(10000, lang('ds_common_op_succ'));
    }

}